<?php
declare (strict_types = 1);

namespace app\controller\api;

use app\BaseController;
use app\model\Delivery as DeliveryModel;
use app\model\Order;
use think\facade\Session;

class Delivery extends BaseController
{
    protected $delivery;
    
    protected function initialize()
    {
        parent::initialize();
        // 检查配送员登录状态
        $token = input('token');
        $this->delivery = DeliveryModel::where('token', $token)->find();
        if (!$this->delivery) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }
    }
    
    /**
     * 配送员登录
     */
    public function login()
    {
        $username = input('post.username');
        $password = input('post.password');
        
        $delivery = DeliveryModel::where('username', $username)->find();
        if (!$delivery || !$delivery->verifyPassword($password)) {
            return json(['code' => 1, 'msg' => '用户名或密码错误']);
        }
        
        if ($delivery->status != 1) {
            return json(['code' => 1, 'msg' => '账号已被禁用']);
        }
        
        // 生成token
        $token = md5($delivery->id . time() . rand(1000, 9999));
        $delivery->token = $token;
        $delivery->save();
        
        return json(['code' => 0, 'data' => ['token' => $token]]);
    }
    
    /**
     * 获取待配送订单
     */
    public function getOrders()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        
        $where = [
            'status' => 1 // 已支付待配送
        ];
        
        $list = Order::where($where)
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select();
            
        $total = Order::where($where)->count();
        
        return json([
            'code' => 0,
            'data' => [
                'total' => $total,
                'list' => $list,
                'page' => $page,
                'limit' => $limit
            ]
        ]);
    }
    
    /**
     * 接单
     */
    public function acceptOrder()
    {
        $orderId = input('order_id/d');
        if (!$orderId) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }
        
        $order = Order::find($orderId);
        if (!$order) {
            return json(['code' => 1, 'msg' => '订单不存在']);
        }
        
        if ($order->status != 1) {
            return json(['code' => 1, 'msg' => '订单状态错误']);
        }
        
        $order->delivery_id = $this->delivery->id;
        $order->status = 2; // 配送中
        $order->delivery_time = date('Y-m-d H:i:s');
        $order->save();
        
        return json(['code' => 0, 'msg' => '接单成功']);
    }
    
    /**
     * 完成配送
     */
    public function completeOrder()
    {
        $orderId = input('order_id/d');
        if (!$orderId) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }
        
        $order = Order::find($orderId);
        if (!$order) {
            return json(['code' => 1, 'msg' => '订单不存在']);
        }
        
        if ($order->delivery_id != $this->delivery->id) {
            return json(['code' => 1, 'msg' => '无权操作此订单']);
        }
        
        if ($order->status != 2) {
            return json(['code' => 1, 'msg' => '订单状态错误']);
        }
        
        $order->status = 3; // 已完成
        $order->complete_time = date('Y-m-d H:i:s');
        $order->save();
        
        return json(['code' => 0, 'msg' => '配送完成']);
    }

    /**
     * 获取配送员列表
     */
    public function index()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $status = input('status/d', -1);
        
        $where = [];
        if ($status >= 0) {
            $where['status'] = $status;
        }
        
        $list = DeliveryModel::getPageList($where, $page, $limit);
        return json(['code' => 0, 'data' => $list]);
    }
    
    /**
     * 添加配送员
     */
    public function add()
    {
        $data = input('post.');
        
        // 验证用户名是否存在
        if (DeliveryModel::where('username', $data['username'])->find()) {
            return json(['code' => 1, 'msg' => '用户名已存在']);
        }
        
        // 密码加密
        $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        
        $delivery = new DeliveryModel;
        $delivery->save($data);
        
        return json(['code' => 0, 'msg' => '添加成功']);
    }
    
    /**
     * 编辑配送员
     */
    public function edit()
    {
        $data = input('post.');
        
        // 验证用户名是否存在
        $delivery = DeliveryModel::where('username', $data['username'])
            ->where('id', '<>', $data['id'])
            ->find();
        if ($delivery) {
            return json(['code' => 1, 'msg' => '用户名已存在']);
        }
        
        // 如果修改密码，则加密
        if (!empty($data['password'])) {
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        } else {
            unset($data['password']);
        }
        
        DeliveryModel::update($data);
        return json(['code' => 0, 'msg' => '编辑成功']);
    }
    
    /**
     * 删除配送员
     */
    public function delete()
    {
        $id = input('id/d');
        if (!$id) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }
        
        DeliveryModel::destroy($id);
        return json(['code' => 0, 'msg' => '删除成功']);
    }
} 